package com.example.order.controller;


import java.util.Random;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.example.order.service.OrderService;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class OrderController {

	private static final String SUCCESS = "SUCCESS";
	private static final String FAIL = "FAIL";

	private final OrderService orderService;
	private final Random random;

	public OrderController(OrderService orderService) {
		this.orderService = orderService;
		this.random = new Random();
	}

	@PostMapping(value = "/order", produces = "application/json")
	@SentinelResource(value = "/order", blockHandler = "orderBlockHandler", fallback = "orderFallback")
	public String order(String userId, String commodityCode, int orderCount) {
		if (random.nextBoolean()) {
			throw new RuntimeException("this is a mock Exception");
		}

		int result = orderService.create(userId, commodityCode, orderCount);
		if (result == 1) {
			return SUCCESS;
		}
		return FAIL;
	}

	// 限流设置
	public String orderBlockHandler(String userId, String commodityCode, int orderCount, BlockException e) {
		return userId + ": 请稍后重试";
	}

	// 熔断降级
	public String orderFallback(String userId, String commodityCode, int orderCount) {
		return userId + ": 熔断降级";
	}
}
